package ec.edu.ups.cidi.siia.plamdep.comunicacionweb.descarga;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.net.ssl.HttpsURLConnection;

import ec.edu.ups.cidi.siia.plamdep.comunicacionweb.Utils.HtmlUtils;
import ec.edu.ups.cidi.siia.plamdep.utils.configuracion.ConfiguracionConexionWeb;

import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
public class DescargarFuente 
{
    public  DescargarFuente ()
    {
        //SetearConfiguraciones
        if( ConfiguracionConexionWeb.htppProxy.length()>0&&ConfiguracionConexionWeb.htppPort.length()>0)
        {   System.setProperty("http.proxyHost",ConfiguracionConexionWeb.htppProxy);
            System.setProperty("http.proxyPort",ConfiguracionConexionWeb.htppPort);
        }
        if( ConfiguracionConexionWeb.htppsProxy.length()>0&&ConfiguracionConexionWeb.htppsPort.length()>0)
        {    
            System.setProperty("https.proxyHost", ConfiguracionConexionWeb.htppsProxy);
            System.setProperty("https.proxyPort",ConfiguracionConexionWeb.htppsPort);
        }
    }
    private  String getProtocolo(String link)
    {
        if(link.startsWith("https"))  return "https";
        return "http";
    }
    
  
    public InputStream descargarAsInputStream(String link)
    {
        link=this.validarLink(link);
        if(this.getProtocolo(link).equals("https")) return this.descargaHTTPS(link);
        return this.descargaHTTP(link);
    }
    /**
     * Convierte un InputStream a un valor String
     */
    private static String getStringFromInputStream(InputStream is) {
		if(is==null)return "";
    	
    	BufferedReader br = null;
		StringBuilder sb = new StringBuilder();
		String line;
		try {
			br = new BufferedReader(new InputStreamReader(is));
			while ((line = br.readLine()) != null) 	sb.append(line);
		} catch (IOException e) {e.printStackTrace();} 
                finally 
                {	if (br != null) 
                            try {  br.close();
				} catch (IOException e) {e.printStackTrace();	}
		}
		return sb.toString();
	}
    
      public  String getStringFromInputStream(final InputStream is, final int bufferSize)
      {
          final char[] buffer = new char[bufferSize];
          final StringBuilder out = new StringBuilder();
          try {
            final Reader in = new InputStreamReader(is, "UTF-8");
            try {
              for (;;) {
                int rsz = in.read(buffer, 0, buffer.length);
                if (rsz < 0)
                  break;
                out.append(buffer, 0, rsz);
              }
            }
            finally {
              in.close();
            }
          }
          catch (Exception ex) {
            /* ... */
          }
      return out.toString();
}
    /**
     * Valida y reconstruye el link en un formto adecuado
     * @param link
     * @return 
     */
    public String validarLink(String link)
    {
        if(link.startsWith("http")==false) link="http://"+link;
        return link;
    }
   
    /**
     * Obtiene el tipo de contenido al que hace referencia un link (pagina,documento,etc..)
     * @param link link a buscar
     */
    public String getTipoContenido(String link)
    {   
    	String contenido="";
    	try{
        link=this.validarLink(link);
        if(this.getProtocolo(link).equals("http")) 
        {
             java.net.URL url = new java.net.URL(link);
             java.net.URLConnection con = url.openConnection();
             contenido= con.getContentType();
        }            
       else 
       { 
          java.net.URL url = new java.net.URL(link);
          HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
          contenido=con.getContentType();
          con.disconnect();
       }
       }catch(Exception ex){System.err.println("Error al obtener el tipo de contenido.....");}
    	if(contenido!=null)
    		return contenido;
        return "text/html; charset=utf-8";
    }
     private InputStream descargaHTTP(String link)
    {   InputStream is=null; 
         try{   java.net.URL url = new java.net.URL(link);
                java.net.URLConnection con = url.openConnection();
                con.setRequestProperty("User-agent","Mozilla/4.0");
                con.setRequestProperty("Accept-Encoding", "gzip, deflate");
                
                String encoding = con.getContentEncoding();
                if (encoding != null && encoding.equalsIgnoreCase("gzip")) is=(new GZIPInputStream(con.getInputStream()));
                else if (encoding != null && encoding.equalsIgnoreCase("deflate")) is=(new InflaterInputStream(con.getInputStream(),new Inflater(true)));
                else    is=(con.getInputStream());
            }catch(Exception e){  e.printStackTrace();  }
        return is;
    }
    private InputStream descargaHTTPS(String link)
    {   try {
                java.net.URL url = new java.net.URL(link);
                HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
                con.setReadTimeout(5000);
                con.setRequestProperty("User-agent","Mozilla/22.0");
                //con.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
                con.setRequestProperty("Accept-Encoding", "gzip, deflate");
                String encoding = con.getContentEncoding();
                System.out.println("formato "+con.getContentType());
                if (encoding != null && encoding.equalsIgnoreCase("gzip"))             return (new GZIPInputStream(con.getInputStream()));
                else if (encoding != null && encoding.equalsIgnoreCase("deflate"))     return (new InflaterInputStream(con.getInputStream(),new Inflater(true)));
                else   return (con.getInputStream());
                
                } catch (IOException ex) 
                {
                        Logger.getLogger(DescargarFuente.class.getName()).log(Level.SEVERE, null, ex);
                }
            return null;
     }   
      Thread    descargaProcess;
    boolean finalizado=false;
    Hilo descarga;
    public String descargarHTML2(String link)
      {
        finalizado=false;
        descarga=new Hilo(link);
        
        descargaProcess=new Thread(descarga);
        descargaProcess.start();
        
        Runnable run=new Runnable()
        {   
            
            public void run() 
            {    try { Thread.sleep(20000); } catch(Exception ex) {}
                 if(descarga.finalizado==false) 
                 { 
                     if(descargaProcess.isAlive())
                            descargaProcess.stop();
                     descarga.continuar=true;
                     System.err.println("Forza continuar");
                     
                     
                   
                 }
            }
        };
        
        Thread hiloTimeOut=new Thread(run);
        hiloTimeOut.start();
        
        while(!descarga.continuar)
        {
            
          try{  Thread.sleep(10); }catch(Exception e){}
        }
        
        return descarga.contenido;
    }
    
    public class Hilo implements Runnable
    {
        public boolean finalizado=false;
        public boolean continuar=false;
        String link;
        public String contenido="";
        public Hilo(String link)
        {
            this.link=link;
        }
        
        public void run() 
        {
            
        link=validarLink(link);
        String content=getTipoContenido(link);
        System.out.println("descargando: "+link +" contenido: "+content );
        InputStream entrada;
        if(getProtocolo(link).equals("https")) entrada= descargaHTTPS(link);
        else entrada=descargaHTTP(link);
        if(content.trim().startsWith("text/html"))
             contenido= getStringFromInputStream(entrada);
        System.out.println("descargando: terinada" );

        continuar=true;
        finalizado=true;
        }
    }
    
    
   /**Voriginal*/ 
     public String descargarHTML(String link)
      {
          String contenido="";
          try{
        link=validarLink(link);
        String content=getTipoContenido(link);
        System.out.println("descargando: "+link +" contenido: "+content );
        InputStream entrada;
        if(getProtocolo(link).equals("https")) entrada= descargaHTTPS(link);
        else entrada=descargaHTTP(link);
        if(content.trim().startsWith("text/html"))
             contenido= getStringFromInputStream(entrada);
        System.out.println("descargando: terinada" );
          }catch(Exception e){e.printStackTrace();}
      
      return contenido;
      }
   
 }